var static = require('node-static');
var fileServer = new static.Server('./public');
var rpc = require('./rpc.js');

// application logic
require('http').createServer(function(request, response) {
    switch (request.method) {
    case 'GET':
        if (request.url == '/') {
            fileServer.serveFile('./index.html',
                                 200, {},
                                 request,
                                 response);
        } else {
            request.addListener('end', function() {
                fileServer.serve(request, response, function(err, res) {
                    if (err != null) {
                        if (err.status === 404) {
                            fileServer.serveFile('./notfound.html',
                                                 404, {},
                                                 request,
                                                 response);
                        } else {
                            response.end();
                        }
                    }
                });
            });
        }
        break;
    case 'POST':
        if (request.url == '/ws') {
            new rpc.Handler(request, response, rpc.methods);
        } else {
            response.writeHead(404);
            response.end();
        }
        break;
    case 'HEAD':
        request.addListener('end', function() {
            if (request.url == '/') {
                response.writeHead(405);
                response.end();
            } else {
                fileServer.serve(request, response);
            }
        });
        break;
    default:
        response.writeHead(501);
        response.end();
    }
}).listen(8080, '0.0.0.0');

console.log('running at port 8080');